package org.iweb.register;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.iweb.scanner.AnnotationScanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings({"rawtypes","unchecked"})
public class RegisterFactory {

	private Map<String, AbstractRegister> registers;

	private static RegisterFactory instance;
	
	protected final static Logger log = LoggerFactory
			.getLogger(RegisterFactory.class);

	private RegisterFactory() {
	}

	public static RegisterFactory getInstance() {
		if (instance == null) {
			instance = new RegisterFactory();
		}
		return instance;
	}

	public Map<String, AbstractRegister> getRegisters() {
		if (registers == null)
			registers = new HashMap<String, AbstractRegister>();
		return registers;
	}

	public AbstractRegister getRegisterByName(String name) {
		return getRegisters().get(name);
	}

	public static void init() {
		getInstance().reload();
	}

	public void reload() {
		try {

			getRegisters().clear();

			AnnotationScanner annotationScanner = new AnnotationScanner();

			List<Class> annotated = annotationScanner
					.getListByAnnotation(Register.class);

			for (Class c : annotated) {

				try {

					Register ann = (Register) c.getAnnotation(Register.class);

					instance.getRegisters().put(ann.name(),
							(AbstractRegister) c.newInstance());

				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}

			for (AbstractRegister as : instance.getRegisters().values()) {
				as.populate(annotationScanner);
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
}
